import shutil
import os
from time import sleep


class FileExtend:

    def __init__(self, path):
        self.path = path

    def moveFile(self, file):
        self.__makeFile(file, shutil.move)
        return file

    def copyFile(self, file):
        self.__makeFile(file, shutil.copy)
        return file

    def __makeFile(self, file, option, loop=1):
        new_file = os.path.join(self.path, os.path.basename(file))
        try:
            option(file, new_file)
        except Exception as error:
            if loop >= 3:
                raise error
            else:
                sleep(0.5)
                self.__makeFile(file, option, loop + 1)

    # 按修改时间从早排序获取文件
    @staticmethod
    def getFileByMtime(path):
        file_list = []
        for f in os.listdir(path):
            file = os.path.join(path, f)
            if os.path.isfile(file):
                file_list.append({'file_path': file, 'mtime': os.path.getmtime(file)})
        file_list.sort(key=(lambda element: element['mtime']))
        return [x['file_path'] for x in file_list]


if __name__ == '__main__':
    print(FileExtend.getFileByMtime(r"G:\BaiduNetdiskDownload"))
